import { add, enable, list } from '@/services/system/user';
import { all } from '@/services/system/role';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Avatar, Button, Drawer, message } from 'antd';
import React, { useRef, useState } from 'react';
import { Md5 } from 'ts-md5';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: SYSTEM.User) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const UserList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<SYSTEM.User>();

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  //data为需要修改的tree，这里主要是为antd design 里面select规范数据
  const convert = (data: any[]) => {
    let department: any[] = [];
    data.forEach((item: any) => {
      let newData: any = {};
      newData.key = item.id;
      newData.value = item.id;
      newData.title = item.name;
      newData.children = item.childDepartment ? convert(item.childDepartment) : []; //如果还有子集，就再次调用自己
      department.push(newData);
    });
    return department;
  };

  const columns: ProColumns<SYSTEM.User>[] = [
    {
      title: <FormattedMessage id="pages.id" defaultMessage="Id" />,
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: <FormattedMessage id="pages.system.user.username" defaultMessage="Username" />,
      dataIndex: 'username',
      width: 200,
    },
    {
      title: <FormattedMessage id="pages.system.user.nickname" defaultMessage="Nickname" />,
      dataIndex: 'nickname',
      width: 180,
    },
    {
      title: <FormattedMessage id="pages.system.user.phone" defaultMessage="Phone" />,
      dataIndex: 'phone',
      width: 160,
    },
    {
      title: <FormattedMessage id="pages.system.user.avatar" defaultMessage="Avatar" />,
      dataIndex: 'avatar',
      render: (dom) => {
        return (
          <a>
            <Avatar size="small" src={dom} />
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.system.user.gender" defaultMessage="Gender" />,
      dataIndex: 'gender',
      hideInForm: true,
      valueEnum: {
        1: {
          text: <FormattedMessage id="pages.male" defaultMessage="Male" />,
          status: 'Processing',
        },
        2: {
          text: <FormattedMessage id="pages.female" defaultMessage="Female" />,
          status: 'Success',
        },
        3: {
          text: <FormattedMessage id="pages.unknown" defaultMessage="Unknown" />,
          status: 'Error',
        },
      },
    },
    {
      title: '账号锁定',
      dataIndex: 'accountNonLocked',
      valueEnum: {
        false: {
          text: '锁定',
          status: 'Error',
        },
        true: {
          text: '未锁定',
          status: 'Success',
        },
      },
    },
    {
      title: '账号启用',
      dataIndex: 'enabled',
      valueEnum: {
        false: {
          text: '禁用',
          status: 'Error',
        },
        true: {
          text: '启用',
          status: 'Success',
        },
      },
    },
    {
      title: <FormattedMessage id="pages.option" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="enable"
          onClick={async () => {
            try {
              console.log(record.enabled);
              await enable({
                id: record.id,
                enalbe: !record.enabled,
              });
              message.success('Configuration is successful');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } catch (error) {
              message.error('Configuration failed, please try again!');
            }
          }}
        >
          {record.enabled ? (
            <FormattedMessage id="pages.status.disable" defaultMessage="Disable" />
          ) : (
            <FormattedMessage id="pages.status.enable" defaultMessage="Enable" />
          )}
        </a>,
        <a key="edit">
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<SYSTEM.User, SYSTEM.UserList>
        headerTitle={intl.formatMessage({
          id: 'pages.system.user.title',
          defaultMessage: 'User List',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.new" defaultMessage="New" />
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.system.user.createModal.title',
          defaultMessage: 'New User',
        })}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          value.password = Md5.hashStr(value.password);
          const success = await handleAdd(value as SYSTEM.User);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="username"
          label={intl.formatMessage({
            id: 'pages.system.user.username',
            defaultMessage: 'Username',
          })}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.system.user.username.rules"
                  defaultMessage="Username is required"
                />
              ),
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          label={intl.formatMessage({
            id: 'pages.system.user.password',
            defaultMessage: 'Password',
          })}
          rules={[
            {
              min: 6,
              max: 50,
              required: true,
              message: (
                <FormattedMessage
                  id="pages.system.user.password.rules"
                  defaultMessage="password length > 6 and < 50"
                />
              ),
            },
          ]}
        />
        <ProFormText
          name="nickname"
          label={intl.formatMessage({
            id: 'pages.system.user.nickname',
            defaultMessage: 'Nickname',
          })}
        />
        <ProFormText
          name="phone"
          label={intl.formatMessage({
            id: 'pages.system.user.phone',
            defaultMessage: 'Phone',
          })}
        />
        <ProFormSelect
          name="roleIds"
          mode="multiple"
          label={intl.formatMessage({
            id: 'pages.system.user.roles',
            defaultMessage: 'Role',
          })}
          placeholder="请选择角色"
          request={async () => {
            let res = await all();
            let roles: any[] = [];
            res.data.forEach((item: SYSTEM.Role) => {
              roles.push({
                label: item.name,
                value: item.id,
              });
            });
            return roles;
          }}
        />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.username && (
          <ProDescriptions<SYSTEM.User>
            column={2}
            title={currentRow?.username}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.username,
            }}
            columns={columns as ProDescriptionsItemProps<SYSTEM.User>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default UserList;
